package com.epfresh.api.global;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.MarketPermissionUtil;
import com.epfresh.supplier.activity.FirstPostAuditActivity;
import com.epfresh.supplier.activity.HomeNewActivity;
import com.epfresh.supplier.activity.LoginActivity;
import com.epfresh.supplier.activity.StoreActivity;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.StaffInfo;
import com.epfresh.supplier.entity.StoreInfo;
import com.epfresh.api.entity.User;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.fragment.HomeNewFragment;
import com.tencent.mmkv.MMKV;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;


/**
 * @author zhaozhenqiang
 */
public class BaseActivity extends AppActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    public BaseApplication getAppApplication() {
        return (BaseApplication) getApplication();
    }

    public User getUser() {
        return getAppApplication().getUser();
    }

    public StoreInfo getStoreInfo() {
        return getAppApplication().getStoreInfo();
    }

    public boolean isDc() {
        return getStoreInfo().isDc();
    }

    public void updateUser(User user) {
        getAppApplication().updateUser(user);
    }

    public void clearUser() {
        getAppApplication().clearUser();
    }

    public void updateStoreInfo(StoreInfo storeInfo) {
        getAppApplication().updateStoreInfo(storeInfo);
    }

    public void clearStoreInfo() {
        getAppApplication().clearStoreInfo();
    }


    //request不能为null
    public <T> void request(Object data, Object tag, final OnRequestListener<T> onRequestListener) {
        L.i("requestJson", data.toString());
        if (getUser() != null && getUser().getPhone() != null) {
            MessageCentre.getInstance().sendAlias(getUser().getPhone());
        } else {
            MessageCentre.getInstance().sendAlias("1");
        }
        if (data instanceof RequestEntitySupply) {
            ((RequestEntitySupply) data).setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            //((RequestEntitySupply) data).setToken(getUser().getToken());
            ((RequestEntitySupply) data).setAppDomain("supplier");
            ((RequestEntitySupply) data).setMerchantId(BaseApplication.getInstance().getMerchantId());
            ((RequestEntitySupply) data).setStoreId(BaseApplication.getInstance().getStoreId());
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = null;
            String appVersion = "";
            try {
                pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
                appVersion = pi.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("os", "android");
            map.put("osVersion", Build.VERSION.RELEASE);
            map.put("model", Build.MODEL);
            map.put("registrationID", JPushInterface.getRegistrationID(this));
            L.d("registation", "registationid:" + JPushInterface.getRegistrationID(this));
            ((RequestEntitySupply) data).setDeviceInfo(map);
            ((RequestEntitySupply) data).setAppVersion(appVersion);
        }

        super.request(data, tag, onRequestListener);
//        HttpRequest request = new HttpRequest(data, new OnRequestListener() {
//            @Override
//            public Object jsonToObj(String responseStr) {
//
//                if (onRequestListener != null) {
//                    return onRequestListener.jsonToObj(responseStr);
//                }
//                return null;
//            }
//
//            @Override
//            public void onFail(int failCode, Object arg, Object tag) {
//                boolean isMain = true;
//                boolean isCurrent = true;
//                if (tag != null && tag instanceof RequestTag) {
//                    RequestTag requestTag = (RequestTag) tag;
//
//                    if (requestTag.type == RequestTag.TYPE_MAIN) {
//                        isMain = true;
//                        isCurrent = false;
//                    } else if (requestTag.type == RequestTag.TYPE_CURRENT) {
//                        isMain = false;
//                        isCurrent = true;
//                    } else if (requestTag.type == RequestTag.TYPE_ALL) {
//                        isMain = true;
//                        isCurrent = true;
//                    }
//                }
//
//                if (isCurrent && onRequestListener != null) {
//                    onRequestListener.onFail(failCode, arg, tag);
//                }
//                if (isMain&& failCode != HttpRequest.FAIL_NO_NET) {
//                    toast(BaseApplication.getDoc().getNetWeak());
//                }
//            }
//
//            @Override
//            public void onResponseError(int failCode, Object arg, Object tag) {
//                L.e("net", "onRequestListener:" + onRequestListener);
//                if (failCode == 403) {
//                    if (BaseApplication.loginActivityCount == 0) {
//                        BaseApplication.loginActivityCount++;
//                        Intent intent = new Intent(getBaseContext(), LoginActivity.class);
//                        intent.putExtra("relogin", true);
//                        startActivityForResult(intent, 0x2379);
//                    }
//                }
//                if (onRequestListener != null) {
//
//                    boolean isMain = true;
//                    boolean isCurrent = true;
//                    if (tag != null && tag instanceof RequestTag) {
//                        RequestTag requestTag = (RequestTag) tag;
//
//                        if (requestTag.type == RequestTag.TYPE_MAIN) {
//                            isMain = true;
//                            isCurrent = false;
//                        } else if (requestTag.type == RequestTag.TYPE_CURRENT) {
//                            isMain = false;
//                            isCurrent = true;
//                        } else if (requestTag.type == RequestTag.TYPE_ALL) {
//                            isMain = true;
//                            isCurrent = true;
//                        }
//                    }
//
//                    L.d("net", "current:" + isCurrent);
//                    L.d("net", "onRequestListener:" + onRequestListener);
//                    if (isCurrent && onRequestListener != null) {
//                        onRequestListener.onResponseError(failCode, arg, tag);
//                    }
//                    if (isMain) {
//                        toast("" + arg);
//                    }
//
//                }
//            }
//
//            @Override
//            public void onStart(Object tag) {
//                if (onRequestListener != null) {
//                    onRequestListener.onStart(tag);
//                }
//            }
//
//            @Override
//            public void onResponse(ResponseEntity response, Object tag) {
//                if (onRequestListener != null) {
//                    onRequestListener.onResponse(response, tag);
//                }
//            }
//        });
//        request.onStart(tag);
//        if (NetworkUtil.isNetworkAvailable(this)) {
//            hideNetWeakView();
//            RetryPolicy retryPolicy = new DefaultRetryPolicy(RequestManager.TIMEOUT_COUNT, RequestManager.RETRY_TIMES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
//            request.setRetryPolicy(retryPolicy);
//            request.setTag(tag);
//            RequestManager.getInstance().request(request);
//        } else {
//            request.onFail(HttpRequest.FAIL_NO_NET, null, tag);
//            showNetWeakView();
//        }
    }


    public void onFail(int failCode, Object arg, Object tag) {

    }

    public void toast(String content) {
        T.toast(content);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x2379 && resultCode == RESULT_OK) {
            reLoginBack();
        }
    }

    protected void reLoginBack() {
    }

    public boolean isReloginBack() {
        return getAppApplication().isReloginBack();
    }

    public void setReloginBack(boolean reloginBack) {
        getAppApplication().setReloginBack(reloginBack);
    }

    public void onLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    //判断是进入主页还是进入开店流程中去
    protected void gotoPage() {
        MerChantInfo merChantInfo = BaseApplication.getInstance().getMerchant();
        //有批发市场权限或者开店成功或者备案过的
        if (MarketPermissionUtil.isMarketPermission(merChantInfo.getStaffInfo()) || merChantInfo.getStoreStatus().equals("2") || merChantInfo.getStoreStatus().equals("4") || !TextUtils.isEmpty(merChantInfo.getSubjectCode())) {
            // StoreActivity.isMain = true;
            MMKV.defaultMMKV().encode("toIndex", 2);
            Intent main = new Intent(getApplicationContext(), HomeNewActivity.class);
            startActivity(main);
            finish();
        } else if (merChantInfo.getStoreStatus().equals("1")) {
            // StoreActivity.isMain = false;
            MMKV.defaultMMKV().encode("toIndex", 1);
            Intent main = new Intent(getApplicationContext(), FirstPostAuditActivity.class);
            startActivity(main);
            finish();
        } else {
            //   StoreActivity.isMain = false;
            MMKV.defaultMMKV().encode("toIndex", 0);
            Intent main = new Intent(getApplicationContext(), StoreActivity.class);
            startActivity(main);
            finish();
        }
    }

    /**
     * 重写getResources()方法，让APP的字体不受系统设置字体大小影响
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}
